<?php

namespace app\common\model;

use think\Db;
use think\Model;
use think\Request;

class Article extends Model
{
    // 表名
    protected $name = 'article';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'status_text'
    ];
    
    const CATE_NOTICE = 14;

    
    public function getStatusList()
    {
        return ['1' => '显示', '0' => '隐藏'];
    }     


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
    
    public function category(){
    	return $this->belongsTo('category', 'category_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	/**
	 * 根据分类查找文章
	 * @param $id
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function getCategoryArticle($id) {
    	$articles =  Db::name('article')
		    ->where(['status' =>1 ,'category_id' => $id])
		    ->field('id, title as name, merid, cover_image, content, from_unixtime(create_time) as time')
		    ->order(['sort' => 'ASC'])
		    ->select();
    	
    	if($articles) {
    		$req = Request::instance();
    	    foreach ($articles as $k => $v) {
    	    	$v['url'] = $req->domain().url('mobile/article/detail',['id' => $v['id'], 'type' => 'app']);
    	    	$articles[$k] = $v;
	        }
	    }
    	
	    return $articles;
    }
}
